package main

import (
	"math/rand"
	"time"
	"sync"
	"fmt"
)

func init(){
	// 设置随机数种子
	rand.Seed(time.Now().UnixNano())
}
const (
	goroutinesNum 	= 4
	taskLoad				=10
)
var wg sync.WaitGroup
func main() {
	task := make(chan string,taskLoad)
	wg.Add(goroutinesNum)
	for i := 1; i <= goroutinesNum; i++ {
		go work(i,task)
	}

	// 送任务
	for post := 1; post<=taskLoad ; post ++{
		task <- fmt.Sprintf("task: %d",post)
	}
	// 关闭
	close(task)

	wg.Wait()
}

func work(i int,taskChan chan string){
	defer wg.Done()
	for {
		task,ok := <- taskChan
		if !ok {
			fmt.Println("the whole task has been completed.")
			return
		}
		fmt.Printf("worker : %d ,Prepare to start the %s \n",i,task)

		// 模拟工作的时间
		sleep := rand.Intn(100)
		time.Sleep(time.Duration(sleep) * time.Millisecond)

		// 显示工作已完成
		fmt.Printf("worker ---> %d have completed the %s \n",i,task)
	}
}
